import { NextRequest } from 'next/server';
import { withMiddleware } from '@/lib/middleware/entry';
import { successResponse, errorResponse } from '@/lib/response';
import { prisma } from '@/lib/prisma';
import { authenticateRequest } from '@/utils/auth';
import { UpdateContentRequest } from '@/types/content';

async function handler(req: NextRequest) {
  const authResult = await authenticateRequest(req);
  if (!authResult.success) {
    return errorResponse(authResult.error || '身份验证失败');
  }

  const { id, categoryIds, cover, isBanner, type, ...data } = (await req.json()) as UpdateContentRequest & { categoryIds: string[]; cover: any };

  const updatedContent = await prisma.$transaction(async (prisma) => {
    await prisma.contentCategory.deleteMany({
      where: { contentId: id },
    });

    return prisma.content.update({
      where: { id },
      data: {
        ...data,
        isBanner,
        type,
        categories: {
          create: categoryIds.map((categoryId) => ({
            category: {
              connect: { id: categoryId },
            },
          })),
        },
      },
      include: {
        cover: true,
      },
    });
  });

  return successResponse(updatedContent, '更新成功');
}

export const POST = withMiddleware(handler);